/**
 * 计时器Web Worker - 确保在页面后台运行时也能精确计时
 */

// 计时器状态管理
let timers = new Map()
let countdowns = new Map()

// 消息处理器
self.onmessage = function(e) {
  const { type, id, data } = e.data
  
  switch (type) {
    case 'START_TIMER':
      startTimer(id, data)
      break
    case 'PAUSE_TIMER':
      pauseTimer(id)
      break
    case 'RESUME_TIMER':
      resumeTimer(id)
      break
    case 'STOP_TIMER':
      stopTimer(id)
      break
    case 'START_COUNTDOWN':
      startCountdown(id, data)
      break
    case 'PAUSE_COUNTDOWN':
      pauseCountdown(id)
      break
    case 'STOP_COUNTDOWN':
      stopCountdown(id)
      break
    case 'RESUME_COUNTDOWN':
      resumeCountdown(id)
      break
    case 'GET_STATUS':
      getStatus(id)
      break
    case 'CLEANUP':
      cleanup()
      break
  }
}

// 开始计时器
function startTimer(id, data) {
  if (timers.has(id)) {
    clearInterval(timers.get(id).interval)
  }
  
  const startTime = Date.now()
  const timer = {
    id,
    startTime,
    duration: 0,
    remaining: 0,
    isRunning: true,
    isPaused: false,
    pausedTime: 0,
    pauseStartTime: null,
    interval: setInterval(() => {
      if (timer.isPaused) return
      
      const currentTime = Date.now()
      const elapsed = Math.floor((currentTime - startTime - timer.pausedTime) / 1000)
      timer.duration = elapsed
      
      self.postMessage({
        type: 'TIMER_UPDATE',
        id,
        data: {
          elapsed,
          isRunning: true,
          isPaused: false
        }
      })
    }, 1000)
  }
  
  timers.set(id, timer)
  
  self.postMessage({
    type: 'TIMER_STARTED',
    id,
    data: { success: true }
  })
}

// 暂停计时器
function pauseTimer(id) {
  const timer = timers.get(id)
  if (timer && timer.isRunning && !timer.isPaused) {
    timer.isPaused = true
    timer.pauseStartTime = Date.now()
    
    self.postMessage({
      type: 'TIMER_PAUSED',
      id,
      data: { success: true }
    })
  }
}
// 通过 pausedTime 累计的总暂停时长，后续可以用来修正实际的有效计时（有效时间 = 总时间 - 总暂停时间）
// 继续计时器
function resumeTimer(id) {
  const timer = timers.get(id)
  if (timer && timer.isRunning && timer.isPaused) {
    timer.isPaused = false
    if (timer.pauseStartTime) {
      timer.pausedTime += Date.now() - timer.pauseStartTime
      timer.pauseStartTime = null
    }
    
    self.postMessage({
      type: 'TIMER_RESUMED',
      id,
      data: { success: true }
    })
  }
}

// 停止计时器
function stopTimer(id) {
  const timer = timers.get(id)
  if (timer) {
    clearInterval(timer.interval)
    timers.delete(id)
    
    self.postMessage({
      type: 'TIMER_STOPPED',
      id,
      data: { success: true }
    })
  }
}

// 开始倒计时
function startCountdown(id, data) {
  if (countdowns.has(id)) {
    clearInterval(countdowns.get(id).interval)
  }
  
  const { duration } = data
  const startTime = Date.now()
  const endTime = startTime + (duration * 1000)
  
  const countdown = {
    id,
    startTime,
    endTime,
    duration,
    remaining: duration,
    isRunning: true,
    isPaused: false,
    pausedTime: 0,
    interval: setInterval(() => {
      if (countdown.isPaused) return
      
      const currentTime = Date.now()
      const elapsed = Math.floor((currentTime - startTime - countdown.pausedTime) / 1000)
      countdown.remaining = Math.max(0, duration - elapsed)
      
      if (countdown.remaining <= 0) {
        // 倒计时结束
        clearInterval(countdown.interval)
        countdown.isRunning = false
        countdowns.delete(id)
        
        self.postMessage({
          type: 'COUNTDOWN_COMPLETED',
          id,
          data: { success: true }
        })
      } else {
        // 更新倒计时
        self.postMessage({
          type: 'COUNTDOWN_UPDATE',
          id,
          data: {
            remaining: countdown.remaining,
            isRunning: true,
            isPaused: false
          }
        })
      }
    }, 1000)
  }
  
  countdowns.set(id, countdown)
  
  self.postMessage({
    type: 'COUNTDOWN_STARTED',
    id,
    data: { success: true }
  })
}

// 暂停倒计时
function pauseCountdown(id) {
  const countdown = countdowns.get(id)
  if (countdown && countdown.isRunning && !countdown.isPaused) {
    countdown.isPaused = true
    countdown.pauseStartTime = Date.now()
    
    self.postMessage({
      type: 'COUNTDOWN_PAUSED',
      id,
      data: { success: true }
    })
  }
}

// 继续倒计时
function resumeCountdown(id) {
  const countdown = countdowns.get(id)
  if (countdown && countdown.isRunning && countdown.isPaused) {
    countdown.isPaused = false
    if (countdown.pauseStartTime) {
      countdown.pausedTime += Date.now() - countdown.pauseStartTime
      countdown.pauseStartTime = null
    }
    
    self.postMessage({
      type: 'COUNTDOWN_RESUMED',
      id,
      data: { success: true }
    })
  }
}

// 停止倒计时
function stopCountdown(id) {
  const countdown = countdowns.get(id)
  if (countdown) {
    clearInterval(countdown.interval)
    countdowns.delete(id)
    
    self.postMessage({
      type: 'COUNTDOWN_STOPPED',
      id,
      data: { success: true }
    })
  }
}

// 获取状态
function getStatus(id) {
  const timer = timers.get(id)
  const countdown = countdowns.get(id)
  
  if (timer) {
    self.postMessage({
      type: 'TIMER_STATUS',
      id,
      data: {
        type: 'timer',
        isRunning: timer.isRunning,
        isPaused: timer.isPaused,
        startTime: timer.startTime,
        pausedTime: timer.pausedTime,
        duration: timer.duration
      }
    })
  } else if (countdown) {
    self.postMessage({
      type: 'COUNTDOWN_STATUS',
      id,
      data: {
        type: 'countdown',
        isRunning: countdown.isRunning,
        isPaused: countdown.isPaused,
        remaining: countdown.remaining,
        duration: countdown.duration
      }
    })
  } else {
    self.postMessage({
      type: 'STATUS_NOT_FOUND',
      id,
      data: { error: 'Timer not found' }
    })
  }
}

// 清理所有计时器
function cleanup() {
  // 清理计时器
  for (const [id, timer] of timers) {
    clearInterval(timer.interval)
  }
  timers.clear()
  
  // 清理倒计时
  for (const [id, countdown] of countdowns) {
    clearInterval(countdown.interval)
  }
  countdowns.clear()
  
  self.postMessage({
    type: 'CLEANUP_COMPLETED',
    data: { success: true }
  })
}

// 定期发送心跳，保持Worker活跃
setInterval(() => {
  self.postMessage({
    type: 'HEARTBEAT',
    data: { timestamp: Date.now() }
  })
}, 30000) // 30秒发送一次心跳
